package com.its.us.web.controller.sys;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.its.us.web.controller.sys.base.BaseWebPaginationCURDController;
import com.its.us.web.entity.sys.Role;
import com.its.us.web.entity.sys.User;
import com.its.us.web.service.sys.UserService;
import com.its.us.web.vo.sys.ResultBean;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author: master
 * @Date: 2020/11/13 23:06
 * @Version: 1.0
 */
@Controller
@RequestMapping("user")
@Slf4j
public class UserController extends BaseWebPaginationCURDController {
    @Resource
    private UserService userService;

    @RequestMapping("init")
    public String init() {
        return "user/init";
    }

    @PostMapping("list")
    @ResponseBody
    @PreAuthorize("hasPermission('/user/init','sys:user:list')")
    public ResultBean list(@RequestBody MultiValueMap<String, String> param) {
        IPage<User> pageData;
        try {
            Map<String, Object> map = super.initParam(param);
            pageData = userService.findByPage(map);
        } catch (Exception e) {
            log.error("用户列表错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(pageData.getTotal(), pageData.getRecords());
    }

    /**
     * 保存或更新
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "保存或更新", notes = "保存或更新操作[更新操作需要传id参数]", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "账户登录名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "账户登录密码", required = true, dataType = "String")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'数据已存在.'}"),
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'数据异常.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("save")
    @ResponseBody
    //@PreAuthorize("hasRole('admin')")
    @PreAuthorize("hasPermission('/user/save','sys:user:save')")
    public ResultBean save(@RequestBody User user){
        ResultBean resultBean;
        try {
            resultBean = userService.saveOrUpdate(user);
        }catch (Exception e){
            log.error("用户保存错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "详情", notes = "根据id查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识id", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:object}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @GetMapping("detail")
    @ResponseBody
    public ResultBean detail(@RequestParam("id") String id){
        User user;
        try {
            user = userService.findById(id);
        }catch (Exception e){
            log.error("账户查询错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(user);
    }

    /**
     * 删除
     *
     * @param ids
     * @param userName
     * @return
     */
    @ApiOperation(value = "删除", notes = "根据ids删除[可以是多个id]", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "标识id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "当前登录人", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("delete")
    @ResponseBody
    //@PreAuthorize("hasRole('admin')")
    @PreAuthorize("hasPermission('/user/delete','sys:user:delete')")
    public ResultBean delete(@RequestParam("ids[]") List<String> ids, @RequestParam("userName") String userName){
        ResultBean resultBean;
        try {
            resultBean = userService.deleteByIds(ids,userName);
        }catch (Exception e){
            log.error("用户删除错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }

    /**
     * 用户角色授权
     *
     * @param roleIds
     * @param userId
     * @return
     */
    @ApiOperation(value = "用户角色授权", notes = "用户角色授权", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleIds", value = "角色ids", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "当前登录人id", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("authRole")
    @ResponseBody
    //@PreAuthorize("hasPermission('/role/authRole','sys:role:authRole')")
    public ResultBean authRole(@RequestParam("roleIds[]") List<String> roleIds, @RequestParam("userId") String userId){
        ResultBean resultBean;
        try {
            resultBean = userService.authRole(roleIds,userId);
        }catch (Exception e){
            log.error("用户角色授权出现错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }

}
